<?php

namespace app\components;

use Yii;
use yii\filters\Cors;
use yii\web\Response;
use yii\filters\RateLimiter;
use yii\filters\AccessControl;
use yii\filters\auth\QueryParamAuth;

class Controller extends \yii\rest\Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        // 跨域限制
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => Yii::$app->params['cors']
        ];

        // 输出格式 json
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;

        // 访问验证 Token
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::class,
            'optional' => ['login']
        ];

        // 访问速率限制
        $behaviors['rateLimiter'] = [
            'class' => RateLimiter::class,
            'enableRateLimitHeaders' => true,
        ];

        //rbac权限验证
        $behaviors['access'] = [
            'class' => AccessControl::class,
            'rules' => [[
                'allow' => true,
                'matchCallback' => function ($rule, $action) {
                    if (isGuest())
                        return true;
                    return true;
                    //$uniqueId = '/' . ltrim($action->getUniqueId(), $this->module->id . '/');
                    //$uniqueId = ('/' . $action->getUniqueId());
                    //$data = Yii::$app->permission->getImplicitPermissionsForNode(Yii::$app->user->id, $uniqueId, 'data', 'field');
                    //return Yii::$app->permission->enforce(Yii::$app->user->id, $uniqueId, 'data', 'field');
                    //return can($uniqueId, getParams());
                }
            ]],
        ];

        return $behaviors;
    }
}